<template>
  <CustomDialog ref="customDialog" width="1000px" :title="dialogProps.title" :isView="dialogProps.isView"
    :onSubmit="handleSubmit" :onClose="handleClose" class="role-dialog">
    <template #header>
      {{ `${dialogProps.title}角色` }}
    </template>
    <template #content>

      <el-form ref="ruleFormRef" :model="dialogProps.row" :rules="rules" class="form-box">
        <el-form-item label="角色名称：" prop="roleName">
          <BInput v-model="dialogProps.row!.roleName" placeholder="请填写角色名称" clearable />
        </el-form-item>

        <div>
          <el-row :gutter="16">
            <el-col :span="8">
              <div class="tree-operation">
                <div class="tree-checked-all"><el-checkbox v-model="checked1" label="全选"
                    @change="handleCheckedAllChange" /></div>
                <!-- <div></div> -->
                <div class="tree-checked-all"><el-checkbox v-model="checked2" label="全部展开"
                    @change="handleExpendAllChange" /></div>
              </div>
            </el-col>
            <el-col :span="12" :offset="4">
              <el-form>
                <el-form-item label="数据权限:">
                  <el-select v-model="dataScope" placeholder="请选择" clearable @change="handleDataPermissions">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <CustomTree ref="treeRef" :treeData="treeFilterData" :avaChecked="true" :alleExpanded="alleExpanded"
                :allChecked="allChecked" @node-checked="handleNodeChecked" @node-click="handleNodeClick"
                :dataScopeValue="dataScopeValue">
                <template v-slot:treeOperation="{ node }">
                  <!-- {{ node }} -->
                  <el-form>
                    <el-form-item label="数据权限:">
                      <el-select v-model="dataScope1" placeholder="请选择" clearable style="width: 50%;">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-form>
                </template>
              </CustomTree>
            </el-col>
          </el-row>

        </div>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="customDialog?.acceptParams(false)">取消</el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, ElTree, FormInstance } from "element-plus";
import CustomDialog from "@/components/Dialog/CustomDialog.vue";
import BInput from "@/components/BaseComponents/BInput.vue";
import SButton from "@/components/SButton/index.vue";
import { getMenuList } from "@/api/basic/role";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import CustomTree from '@/components/CustomTree/index.vue'

const rules = reactive({
  roleName: [{ required: true, message: "请填写角色名称" }]
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {},
});

const checked1 = ref(false)
const checked2 = ref(false)
const dataScope = ref<any>()
const dataScope1 = ref<any>()
const options = [
  {
    value: 1,
    label: '全部'
  },
  {
    value: 2,
    label: '所属部门'
  },
  {
    value: 3,
    label: '所属部门及下级部门'
  },
  {
    value: 4,
    label: '全部数据'
  },
  {
    value: 5,
    label: '指定单位/部门'
  }
]

const customDialog = ref<InstanceType<typeof CustomDialog>>();

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  // dialogProps.value = params;
  //修改，使新增时数据不清除
  dialogProps.value.api = params.api;
  dialogProps.value.getTableList = params.getTableList;
  dialogProps.value.title = params.title;
  dialogProps.value.isView = params.isView;
  if (JSON.stringify(params.row) !== '{}') {
    dialogProps.value.row = params.row;
  }
  customDialog.value?.acceptParams(true);
};

watch(
  () => dialogProps.value,
  (newValue) => {
    // console.log('66666', newValue);
  }
);

//获取菜单列表
const treeFilterData = ref<any>()
const menuList = ref<any>()
const obtainTheMenuList = async () => {
  const res = await getMenuList();
  treeFilterData.value = convertToTreeData(res);
  console.log('res', treeFilterData.value);

  menuList.value = res
};
obtainTheMenuList()


const treeRef = ref<any>(null);
// 树形数据转成需要的数据
// interface TreeNode {
//   id: number;
//   label: string;
//   expanded: boolean;
//   checked: boolean;
//   disabled: boolean;
//   indeterminate: boolean;
//   parentId: number;
//   children?: TreeNode[];
//   isLast?: boolean;
// }

// interface MenuItem {
//   id: number;
//   menuName: string;
//   parentId: number;
//   orderNum: number | null;
//   url: string | null;
//   target: string | null;
//   menuType: string;
//   visible: number;
//   perms: string;
//   menuPermissionsDtoList?: MenuItem[];
//   buttonPermissionDtoList?: MenuItem[];
// }

// const convertToTreeData = (menuItems: MenuItem[]): TreeNode[] => {
//   const treeData: TreeNode[] = [];
//   const convertNode = (menuItem: MenuItem): TreeNode => {
//     const node: TreeNode = {
//       id: menuItem.id,
//       label: menuItem.menuName,
//       expanded: false,
//       checked: false,
//       disabled: false,
//       indeterminate: false,
//       parentId: menuItem.parentId,
//       isLast: false
//     };

//     if (menuItem.menuPermissionsDtoList) {
//       node.children = menuItem.menuPermissionsDtoList.map(convertNode);
//     }

//     if (menuItem.buttonPermissionDtoList) {
//       if (!node.children) {
//         node.children = [];
//         node.isLast = true
//       }
//       node.children.push(...menuItem.buttonPermissionDtoList.map(convertNode));
//       node.isLast = true
//     }

//     return node;
//   };

//   menuItems.forEach(menuItem => {
//     treeData.push(convertNode(menuItem));
//   });

//   return treeData;
// };


interface MenuItem {
  id: number;
  menuName: string;
  parentId: number;
  menuPermissionsDtoList?: MenuItem[];
  buttonPermissionDtoList?: MenuItem[];
}

interface TreeNode {
  id: number;
  label: string;
  expanded: boolean;
  checked: boolean;
  disabled: boolean;
  indeterminate: boolean;
  parentId: number;
  isLast: boolean;
  children?: TreeNode[];
  isLastLayer: boolean;
}

const convertToTreeData = (menuItems: MenuItem[]): TreeNode[] => {
  const setLastNodeFlag = (nodes: TreeNode[]) => {
    if (nodes.length > 0) {
      nodes[nodes.length - 1].isLast = true;
    }
  };

  const convertNode = (menuItem: MenuItem): TreeNode => {
    const node: TreeNode = {
      id: menuItem.id,
      label: menuItem.menuName,
      expanded: false,
      checked: false,
      disabled: false,
      indeterminate: false,
      parentId: menuItem.parentId,
      isLast: false,
      children: [],
      isLastLayer: false
    };

    if (menuItem.menuPermissionsDtoList) {
      node.children = menuItem.menuPermissionsDtoList.map(convertNode);
      // setLastNodeFlag(node.children);
    }

    if (menuItem.buttonPermissionDtoList) {
      const buttonNodes = menuItem.buttonPermissionDtoList.map(convertNode);
      node.children?.push(...buttonNodes);
      if (node.children) {
        setLastNodeFlag(node.children);
        node.children.forEach(buttonNode => {
          buttonNode.isLastLayer = true;
        });
      }
    }

    return node;
  };

  const treeData: TreeNode[] = menuItems.map(convertNode);
  setLastNodeFlag(treeData);

  return treeData;
};



//选中
const handleNodeChecked = (node: any) => {

}

//点击
const handleNodeClick = (node: any) => {

}

//全选
const allChecked = ref(true)
const handleCheckedAllChange = (val: boolean) => {
  allChecked.value = val
  if (val && treeRef.value) {
    treeRef.value?.selectAll()
  } else if (!val && treeRef.value) {
    treeRef.value?.unSelectAll()
  }
}

//展开/缩回
const alleExpanded = ref(true)
const handleExpendAllChange = (val: boolean) => {
  alleExpanded.value = val
  if (val && treeRef.value) {
    treeRef.value?.expandAll()
  } else if (!val && treeRef.value) {
    treeRef.value?.collapseAll()
  }
}

//数据权限
const dataScopeValue = ref<any>()
const handleDataPermissions = (val: any) => {
  console.log(val);
  if (val) {
    dataScopeValue.value = Number(val)
  }
}




// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
// ProTable 实例
const proTable = ref<ProTableInstance>();


const handleSubmit = async () => {
};

const handleClose = () => {
  customDialog.value?.acceptParams(false);
};

defineExpose({
  acceptParams
});




</script>

<style lang="scss" scoped>
//设置对话框的高度不变
:deep(.el-tabs__content) {
  height: 430px;
}

//设置tabs
.steps-tabs {
  :deep(.el-tabs__nav-wrap:after) {
    background-color: unset;
  }

  :deep(.el-tabs__nav) {
    float: none;
    display: flex;
    justify-content: center;
  }
}

//表单
.form-box {
  width: 60%;
  margin: 0 auto;
}

.tree-table-box {
  display: flex;
  justify-content: space-around;

  .left-tree-box {
    width: 20%;
    height: 430px;
    overflow: hidden;

    //设置滚动
    .left-checkbox {
      width: 100%;
      max-height: 400px;
      overflow-y: auto;
    }
  }

  .left-table-box {
    width: 78%;
    margin-left: 2%;
    max-height: 400px;
    overflow-y: auto;

    .header-box {
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;

      .header-title {
        width: 100%;
        text-align: center;
        font-size: 1rem;
        background-color: #f2f2f2;
        padding: 1rem 0;
        box-sizing: border-box
      }

      .checkbox-box {
        width: 100%;
        margin: 0.5rem 0;
        display: flex;
        align-items: center;

        justify-content: flex-start;

        div {
          margin-right: 0.5rem;
        }
      }
    }

    :deep(.table-main) {
      width: 100%;
      height: auto;
    }
  }
}

.tree-operation {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .tree-checked-all {
    // margin-right: 2rem;
    // flex: 1;
  }
}
</style>
